package com.demo.lifeinfo.widget;

import android.content.Context;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.ToastUtils;
import com.demo.lifeinfo.R;
import com.demo.lifeinfo.entity.Comment;
import com.demo.lifeinfo.entity.News;
import com.demo.lifeinfo.entity.User;
import com.flyco.roundview.RoundTextView;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BottomPopupView;
import com.lxj.xpopup.impl.LoadingPopupView;

import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;

/**
 * created by Raymond
 * on 2019-04-29
 */
public class CustomEditPopup extends BottomPopupView {
    private LoadingPopupView loadingPopupView;
    EditText edit_text;
    RoundTextView send;
    News news;
    Context context;

    public CustomEditPopup(@NonNull Context context, News news) {
        super(context);
        this.context = context;
        this.news = news;
    }


    @Override
    protected int getImplLayoutId() {
        return R.layout.popupview_edit;

    }

    @Override
    protected void onCreate() {
        super.onCreate();
        edit_text = findViewById(R.id.edit_text);
        send = findViewById(R.id.btn_send);
        send.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(edit_text.getText().toString())) {
                    return;
                }
                sendCommend(news, edit_text.getText().toString());

            }
        });
    }

    void sendCommend(News news, String string) {
        showProgressDialog();
        ToastUtils.setGravity(Gravity.CENTER, 0, 0);
        Comment comment = new Comment();
        comment.setNews(news);
        comment.setPublisher(BmobUser.getCurrentUser(User.class));
        comment.setText(string);
        comment.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                dimssProgressDialog();
                if (e == null) {
                    ToastUtils.showLong("评论成功！");
                } else {
                    ToastUtils.showLong(e.getMessage());
                }
                dismiss();
            }
        });
    }

    public void showProgressDialog() {
        if (loadingPopupView == null)
            loadingPopupView = new XPopup.Builder(context).asLoading();

        loadingPopupView.show();
    }

    public void dimssProgressDialog() {
        if (loadingPopupView != null)
            loadingPopupView.dismiss();
    }
}
